import datetime,json,multiprocessing,os,json,sys
import pandas as pd
import numpy as np
import copy

def main():
	print(f"input_file: {sys.argv[1]}")
	print(f"output_ok: {sys.argv[2]}")
	print(f"output_err: {sys.argv[3]}")

	input_path = os.path.join(os.getcwd(), sys.argv[1])
	input_dict = pd.read_csv(input_path, sep='|', names=['c1','c2','c3','c4'], skiprows=0).to_dict(orient='records')

	output_ok = os.path.join(os.getcwd(), sys.argv[2])
	output_err = os.path.join(os.getcwd(), sys.argv[3])

	output_ok_handle = open(output_ok, 'w', encoding='utf-8')
	#output_err_handle = open(output_err, 'w', encoding='utf-8')

	input_hash = {}

	with open(input_path, encoding='utf-8') as input_file:
		for line in input_file.readlines():
			if line.isspace():
				print(line)
				continue
			r = line.strip('\n').split('|')

			if len(r[-1].split(',')) > 1:
				r[-1] = str([uid for uid in r[-1].split(',') if str(uid).isdigit() and str(uid) != '0'][-1])

			input_hash[r[0]] = r
	
	tt = []
	cnt = 0
	
	for r in input_dict:
		cnt += 1
		t = []
		if not pd.isna(r.get('c4')):
			if len(r.get('c4').split(',')) == 1:
				t.extend([str(r.get('c2')), str(r.get('c3'))]*3)
				tt.append({'row': cnt, 'type': 'T_001', 'values': t})
			else:
				serch_uids = [uid for uid in r.get('c4').split(',') if str(uid).isdigit() and str(uid) != '0'][-1]
				#print(r)
				out_c1 = r.get('c2')
				out_c2 = r.get('c3')
				level = 1

				if serch_uids not in input_hash:
					t.extend([str(out_c1), str(out_c2)]*3)
					tt.append({'row': cnt, 'type': 'T_002', 'values': t})
					continue

				t.extend([str(out_c1), str(out_c2)])

				while serch_uids in input_hash:
					#print(level, r)
					tmp = input_hash.get(serch_uids)
					#print(tmp)
					serch_uids = tmp[-1]
					level += 1

					if serch_uids != '0':
						t.extend([tmp[1], tmp[2]])
					else:
						t.extend([tmp[1], tmp[2]])
						break
				
				tt.append({'row': cnt, 'type': 'T_003', 'values': t})
		else:
			print(r)

	unlink_level = {
		'T_003_01': ['aa', 'aa', 'aa'],
		'T_003_02': ['bb', 'bb', 'bb', 'bb'],
		'T_003_03': ['cc', 'cc'],
		'T_003_04': ['dd', 'dd', 'dd'],
		'T_003_05': ['ee', 'ee', 'ee'],
		'T_003_06': ['ff', 'ff', 'ff'],
		'T_003_07': ['gg', 'gg', 'gg', 'gg'],
		'T_003_08': ['hh', 'hh', 'hh', 'hh', 'hh'],
		'T_003_09': ['ii', 'ii', 'ii', 'ii', 'ii'],
		'T_003_10': ['jj', 'jj', 'jj', 'jj'],
		'T_003_11': ['kk', 'kk', 'kk', 'kk'],
		'T_003_12': ['ll', 'll'],
		'T_003_13': ['mm', 'mm'],
		'T_003_14': ['oo', 'oo', 'oo'],
		'T_003_15': ['pp', 'pp'],
		'T_003_16': ['qq', 'qq'],
		'T_003_17': ['rr', 'rr', 'rr'],
		'T_003_18': ['ss', 'ss', 'ss', 'ss'],
		'T_003_19': ['tt', 'tt'],
		'T_003_20': ['yy', 'yy', 'yy']
	}

	#ttt = copy.deepcopy(tt)

	#tt = tt[42028:42032]
	#print(tt[3770:3774])
	#print(tt[3770:3774])
	
	for i in tt[:]:
		i['max_len'] = len(i.get('values'))
		if i.get('type') == 'T_003':
			a = [j for j in i.get('values') if not str(j).isdigit()]
			if a == ['aa', 'aa']:
				print(i)
			elif a == ['bb', 'bb', 'bbb']:
				print(i)

			for t in unlink_level:

				if a == unlink_level.get(t):
					i['type'] = t
					#print(t, i)
			#print(i)
			if i.get('type') == 'T_003_01':
				#print('1', i)
				t1 = {'type': 'T_001_01', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_01', 'values': i.get('values')[2:4]*3}
				t3 = {'type': 'T_001_01', 'values': i.get('values')[4:6]*3}
				tt.append(t1)
				tt.append(t2)
				tt.append(t3)
				tt.remove(i)
				#pass
			elif i.get('type') == 'T_003_02':
				#pass
				#print(i)
				t1 = {'type': 'T_001_02', 'values': i.get('values')[0:2]*3}
				# 12.19 保留中间链路，中间不断开
				#t2 = {'type': 'T_001_02', 'values': i.get('values')[2:4]*3}
				#t3 = {'type': 'T_001_02', 'values': i.get('values')[4:6]*3}
				t4 = {'type': 'T_001_02', 'values': i.get('values')[6:8]*3}
				tt.append(t1)
				#tt.append(t2)
				#tt.append(t3)
				tt.append(t4)
				#tt.remove(i)
				i['values'] = i.get('values')[2:6] + i.get('values')[4:6]
			elif i.get('type') == 'T_003_03':
				#pass
				print(i)
			elif i.get('type') == 'T_003_04':
				#pass
				#print(i)
				#print('1', i)
				t1 = {'type': 'T_001_04', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_04', 'values': i.get('values')[2:4]*3}
				t3 = {'type': 'T_001_04', 'values': i.get('values')[4:6]*3}
				tt.append(t1)
				tt.append(t2)
				tt.append(t3)
				tt.remove(i)
			elif i.get('type') == 'T_003_05':
				#pass
				#print(i)
				t1 = {'type': 'T_001_05', 'values': i.get('values')[4:6]*3}
				tt.append(t1)
				i['values'] = i.get('values')[0:4] + i.get('values')[2:4]
				#print(i)
			elif i.get('type') == 'T_003_06':
				#pass
				#print(i)
				t1 = {'type': 'T_001_06', 'values': i.get('values')[4:6]*3}
				tt.append(t1)
				i['values'] = i.get('values')[0:4] + i.get('values')[2:4]
			elif i.get('type') == 'T_003_07':
				#pass
				t1 = {'type': 'T_001_07', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_07', 'values': i.get('values')[6:8]*3}
				tt.append(t1)
				tt.append(t2)
				i['values'] = i.get('values')[2:6] + i.get('values')[4:6]
			elif i.get('type') == 'T_003_08':
				#pass
				#print(i)
				t1 = {'type': 'T_001_08', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_08', 'values': i.get('values')[8:10]*3}
				tt.append(t1)
				tt.append(t2)
				i['values'] = i.get('values')[2:8]
				#print(i)
			elif i.get('type') == 'T_003_09':
				#pass
				#print(i)
				t1 = {'type': 'T_001_09', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_09', 'values': i.get('values')[8:10]*3}
				tt.append(t1)
				tt.append(t2)
				i['values'] = i.get('values')[2:8]
			elif i.get('type') == 'T_003_10':
				#print(i)
				#pass
				t1 = {'type': 'T_001_10', 'values': i.get('values')[6:8]*3}
				tt.append(t1)
				i['values'] = i.get('values')[0:6]
				#print(i)
			elif i.get('type') == 'T_003_11':
				#print(i)
				#pass
				t1 = {'type': 'T_001_11', 'values': i.get('values')[6:8]*3}
				tt.append(t1)
				i['values'] = i.get('values')[0:6]
				#print(i)
			elif i.get('type') == 'T_003_12':
				#pass
				#print(i)
				t1 = {'type': 'T_001_12', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_12', 'values': i.get('values')[2:4]*3}
				tt.append(t1)
				tt.append(t2)
				tt.remove(i)
			elif i.get('type') == 'T_003_13':
				#pass
				#print(i)
				t1 = {'type': 'T_001_13', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_13', 'values': i.get('values')[2:4]*3}
				tt.append(t1)
				tt.append(t2)
				tt.remove(i)
			elif i.get('type') == 'T_003_14':
				#pass
				#print(i)
				t1 = {'type': 'T_001_14', 'values': i.get('values')[4:6]*3}
				tt.append(t1)
				i['values'] = i.get('values')[0:4] + i.get('values')[2:4]
			elif i.get('type') == 'T_003_15':
				#pass
				#print(i)
				t1 = {'type': 'T_001_15', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_15', 'values': i.get('values')[2:4]*3}
				tt.append(t1)
				tt.append(t2)
				tt.remove(i)
			elif i.get('type') == 'T_003_16':
				#pass
				#print(i)
				t1 = {'type': 'T_001_16', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_16', 'values': i.get('values')[2:4]*3}
				tt.append(t1)
				tt.append(t2)
				tt.remove(i)
			elif i.get('type') == 'T_003_17':
				#pass
				#print(i)
				t1 = {'type': 'T_001_17', 'values': i.get('values')[0:2]*3}
				tt.append(t1)
				i['values'] = i.get('values')[2:6] + i.get('values')[4:6]
				#print(i)
			elif i.get('type') == 'T_003_18':
				t1 = {'type': 'T_001_18', 'values': i.get('values')[0:2]*3}
				tt.append(t1)
				i['values'] = i.get('values')[2:8]
			elif i.get('type') == 'T_003_19':
				t1 = {'type': 'T_001_19', 'values': i.get('values')[0:2]*3}
				t2 = {'type': 'T_001_19', 'values': i.get('values')[2:4]*3}
				tt.append(t1)
				tt.append(t2)
				tt.remove(i)
			elif i.get('type') == 'T_003_20':
				#print(i)
				t1 = {'type': 'T_001_07', 'values': i.get('values')[0:2]*3}
				tt.append(t1)
				i['values'] = i.get('values')[2:6] + i.get('values')[4:6]
				#print(i)
			else:
				if len(i.get('values')) == 4 and i.get('values')[-1] in ['BSTR', 'ESTR']:
					#print(len(i.get('values')), i)
					t1 = {'type': 'T_001_99', 'values': i.get('values')[0:2]*3}
					t2 = {'type': 'T_001_99', 'values': i.get('values')[2:4]*3}
					tt.append(t1)
					tt.append(t2)
					tt.remove(i)
				elif len(i.get('values')) == 4 and i.get('values')[-1] not in ['BSTR', 'ESTR']:
					#print(i)
					i['values'] = i.get('values')[0:4] + i.get('values')[2:4]
					#print(i)
					#pass
				elif len(i.get('values')) == 6 and i.get('values')[-1] in ['BSTR', 'ESTR']:
					#print(i)
					t1 = {'type': 'T_001_98', 'values': i.get('values')[4:6]*3}
					tt.append(t1)
					i['values'] = i.get('values')[0:4] + i.get('values')[2:4]
				elif len(i.get('values')) == 8 and i.get('values')[-1] in ['BSTR', 'ESTR']:
					#print(i)
					t1 = {'type': 'T_001_97', 'values': i.get('values')[6:8]*3}
					tt.append(t1)
					i['values'] = i.get('values')[0:6]
				else:
					pass
		elif i.get('type') == 'T_002':
			#print(i)
			pass
		else:
			#print(i)
			pass

	result = list(set(tuple(row.get('values')) for row in tt))
	for l in result:
		out = '|'.join([
			str(l[0]),
			str(l[1]),
			str(l[2]),
			str(l[3]),
			str(l[4]),
			str(l[5]),
		]) + '\n'
		output_ok_handle.write(out)
	output_ok_handle.close()

if __name__ == '__main__':
	time1 = datetime.datetime.now()
	main()
	time2 = datetime.datetime.now()

	print('start time: ', time1)
	print('end time: ', time2)
	print('total time: ', time2 - time1)
